package com.my.style.utils;

import android.content.Context;
import android.util.Log;

import org.xutils.DbManager;
import org.xutils.db.table.TableEntity;
import org.xutils.x;

/**
 * Created by Administrator on 2017/6/26.
 */

public class DatabaseHelper {
    public static final String DB_NAME = "BookStore.db";
    public static final int DB_VERSION = 1;
    private static DatabaseHelper instance = null;
    private static DbManager dbManager = null;
    private static Context ct;

    private DatabaseHelper(Context ct) {
        DatabaseHelper.ct = ct;
    }

    public static DatabaseHelper getInstance(Context ct) {
        synchronized (DatabaseHelper.class) {
            if (null == instance) {
                instance = new DatabaseHelper(ct);
            }
        }
        return instance;
    }

    public DbManager getManager() {
        return dbManager;
    }

    private static DbManager getDBManager() {
        synchronized (DbManager.class) {
            if (null == dbManager) {
                /**
                 * 初始化DaoConfig配置
                 */
                DbManager.DaoConfig daoConfig = new DbManager.DaoConfig()
                        //设置数据库名，默认xutils.db
                        .setDbName(DB_NAME)
                        //设置数据库路径，默认存储在app的私有目录
                        // .setDbDir(new File("/mnt/sdcard/"))
                        //设置数据库的版本号
                        .setDbVersion(DB_VERSION)
                        //设置数据库打开的监听
                        .setDbOpenListener(new DbManager.DbOpenListener() {
                            @Override
                            public void onDbOpened(DbManager db) {
                                //开启数据库支持多线程操作，提升性能，对写入加速提升巨大
                                db.getDatabase().enableWriteAheadLogging();
                            }
                        })
                        //设置数据库更新的监听
                        .setDbUpgradeListener(new DbManager.DbUpgradeListener() {
                            @Override
                            public void onUpgrade(DbManager db, int oldVersion, int newVersion) {
                            }
                        })
                        //设置表创建的监听
                        .setTableCreateListener(new DbManager.TableCreateListener() {
                            @Override
                            public void onTableCreated(DbManager db, TableEntity<?> table) {
                                Log.i("JAVA", "onTableCreated：" + table.getName());
                            }
                        });
                //设置是否允许事务，默认true
                //.setAllowTransaction(true)
                dbManager = x.getDb(daoConfig);
            }
        }
        return dbManager;
    }
}
